package com.hph.health.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hph.health.common.BaseResponse;
import com.hph.health.common.ErrorCode;
import com.hph.health.common.ResultUtils;
import com.hph.health.exception.BusinessException;
import com.hph.health.exception.ThrowUtils;
import com.hph.health.model.dto.order.MyOrderList;
import com.hph.health.model.dto.product.ProductAddRequest;
import com.hph.health.model.dto.product.ProductCountUpdateRequest;
import com.hph.health.model.dto.product.ProductQueryRequest;
import com.hph.health.model.dto.product.ProductUpdateRequest;
import com.hph.health.model.dto.user.DeleteRequest;
import com.hph.health.model.entity.Order;
import com.hph.health.model.entity.Product;
import com.hph.health.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

/**
 * 商品接口
 *
 * @author hanph
 * @from haut
 */
@RestController
@RequestMapping("/product")
@Slf4j
public class ProductController {
    @Resource
    private ProductService productService;

    @Resource
    private OrderController orderController;

    /**
     * 分页获取商品列表
     *
     * @param productQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    public BaseResponse<Page<Product>> listProductByPage(@RequestBody ProductQueryRequest productQueryRequest) {
        long current = productQueryRequest.getCurrent();
        long size = productQueryRequest.getPageSize();
        Page<Product> userPage = productService.page(new Page<>(current, size),
                productService.getQueryWrapper(productQueryRequest));
        return ResultUtils.success(userPage);
    }

    /**
     *  创建商品
     *
     * @param productAddRequest
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addProduct(@RequestBody ProductAddRequest productAddRequest) {
        if (productAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Product product = new Product();
        BeanUtils.copyProperties(productAddRequest, product);
        boolean result = productService.save(product);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(product.getId());
    }
    /**
     * 删除商品
     *
     * @param deleteRequest
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteProduct(@RequestBody DeleteRequest deleteRequest) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        return ResultUtils.success(productService.removeById(deleteRequest.getId()));
    }

    /**
     * 更新商品
     *
     * @param productUpdateRequest
     * @return
     */
    @PostMapping("/update")
    public BaseResponse<Boolean> updateProduct(@RequestBody ProductUpdateRequest productUpdateRequest) {
        if (productUpdateRequest == null || productUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Product product = new Product();
        BeanUtils.copyProperties(productUpdateRequest, product);
        boolean result = productService.updateById(product);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 更新商品余额
     *
     * @param productCountUpdateRequest
     * @return
     */
    @PostMapping("/updateproductCount")
    public BaseResponse<Boolean> updateproductCountProduct(@RequestBody ProductCountUpdateRequest productCountUpdateRequest) {
        if (productCountUpdateRequest == null || productCountUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Product product = new Product();
        BeanUtils.copyProperties(productCountUpdateRequest, product);
        boolean result = productService.updateById(product);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取商品
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<Product> getUserById(long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Product product = productService.getById(id);
        ThrowUtils.throwIf(product == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(product);
    }
    /**
     * 分页获取商品列表(协同过滤算法简单实现)
     *
     * @param productQueryRequest
     * @return
     */
    @PostMapping("/list/page/sort")
    public BaseResponse<Page<Product>> listmyProductByPage(@RequestBody ProductQueryRequest productQueryRequest) {
        long current = productQueryRequest.getCurrent();
        long size = productQueryRequest.getPageSize();
        ThrowUtils.throwIf(size > 100, ErrorCode.PARAMS_ERROR);
        Page<Product> userPage = productService.page(new Page<>(current, size),
                productService.getQueryWrapper(productQueryRequest));
        MyOrderList myOrderList = new MyOrderList();
        myOrderList.setUserId(productQueryRequest.getUserId());
        BaseResponse<List<Order>> orderByPage = orderController.listmyOrderByPage(myOrderList);
        List<String> productIdList = new ArrayList<>();
        List<Order> orderList = orderByPage.getData();
        if (orderList != null) {
            for (Order order : orderList) {
                productIdList.add(order.getProductId());
            }
        }
        List<String> categoryList = new ArrayList<>();
        for (String productId : productIdList) {
            long productIdLong = Long.parseLong(productId);
            Product product = productService.getById(productIdLong);
            categoryList.add(product.getCategory());
        }
        Map<String, Integer> categoryCountMap = new HashMap<>();
        for (String category : categoryList) {
            categoryCountMap.put(category, categoryCountMap.getOrDefault(category, 0) + 1);
        }
        List<Map.Entry<String, Integer>> entryList = new ArrayList<>(categoryCountMap.entrySet());
        entryList.sort((entry1, entry2) -> entry2.getValue().compareTo(entry1.getValue()));
        ArrayList<String> sortedCategoryList = new ArrayList<>();
        for (Map.Entry<String, Integer> entry : entryList) {
            String category = entry.getKey();
            int count = entry.getValue();
            for (int i = 0; i < count; i++) {
                sortedCategoryList.add(category);
            }
        }
        Map<String, Integer> categoryIndexMap = new HashMap<>();
        for (int i = 0; i < sortedCategoryList.size(); i++) {
            categoryIndexMap.put(sortedCategoryList.get(i), i);
        }
        Comparator<Product> categoryComparator = Comparator.comparingInt(p -> categoryIndexMap.getOrDefault(p.getCategory(),
                Integer.MAX_VALUE));
        userPage.getRecords().sort(categoryComparator);
        return ResultUtils.success(userPage);
    }
}
